'use client'

import { useEffect, useState } from 'react'

export default function DashboardPage() {
  const [totalSales, setTotalSales] = useState<number>(0)
  const [totalUsers, setTotalUsers] = useState<number>(0)
  const [totalStock, setTotalStock] = useState<number>(0)
  const [recentSales, setRecentSales] = useState<any[]>([])

  useEffect(() => {
    async function fetchData() {
      try {
        // 获取总销售额
        const salesResponse = await fetch('/api/sales')
        if (!salesResponse.ok) {
          throw new Error('获取销售数据失败')
        }
        const salesData = await salesResponse.json()
        console.log('销售数据:', salesData) // 打印销售数据
        const total = salesData.reduce((sum: number, sale: any) => sum + (parseFloat(sale.totalAmount) || 0), 0) // 确保总销售额是数字
        setTotalSales(total)

        // 获取总用户数
        const usersResponse = await fetch('/api/users')
        if (!usersResponse.ok) {
          throw new Error('获取用户数据失败')
        }
        const usersData = await usersResponse.json()
        console.log('用户数据:', usersData) // 打印用户数据
        setTotalUsers(usersData.length)

        // 获取总库存量
        const productsResponse = await fetch('/api/products')
        if (!productsResponse.ok) {
          throw new Error('获取产品数据失败')
        }
        const productsData = await productsResponse.json()
        console.log('产品数据:', productsData) // 打印产品数据
        const totalStockCount = productsData.reduce((sum: number, product: any) => sum + (parseInt(product.stock) || 0), 0) // 确保总库存量是数字
        setTotalStock(totalStockCount)

        // 获取最近的销售记录
        const recentSalesResponse = await fetch('/api/sales/recent')
        if (!recentSalesResponse.ok) {
          throw new Error('获取最近销售记录失败')
        }
        const recentSalesData = await recentSalesResponse.json()
        console.log('最近销售记录:', recentSalesData) // 打印最近销售记录
        setRecentSales(recentSalesData)
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    }

    fetchData()
  }, [])

  return (
    <div className="p-8 bg-gray-50">
      <h1 className="text-2xl font-bold text-gray-900">仪表盘</h1>
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
        <div className="bg-white p-4 rounded shadow">
          <h2 className="text-lg font-semibold text-gray-800">总销售额</h2>
          <p className="text-2xl text-green-600">¥{totalSales.toFixed(2)}</p>
        </div>
        <div className="bg-white p-4 rounded shadow">
          <h2 className="text-lg font-semibold text-gray-800">总用户数</h2>
          <p className="text-2xl text-blue-600">{totalUsers}</p>
        </div>
        <div className="bg-white p-4 rounded shadow">
          <h2 className="text-lg font-semibold text-gray-800">总库存量</h2>
          <p className="text-2xl text-orange-600">{totalStock}</p>
        </div>
      </div>
      <div className="bg-white p-4 rounded shadow mt-4">
        <h2 className="text-lg font-semibold text-gray-800">最近的销售记录</h2>
        <ul>
          {recentSales.map(sale => (
            <li key={sale.id} className="border-b border-gray-300 p-2 text-gray-800">
              <span>销售编号: {sale.code}</span> - <span>总金额: ¥{parseFloat(sale.totalAmount).toFixed(2)}</span>
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}